package com.xjscrm.console.aop;

import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.result.ResponseResult;
import com.xjscrm.console.anno.NoResponseResult;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * <p>
 * Controller Aop
 * 获取响应结果信息
 * </p>
 */
@Aspect
@Component
public class ResponseResultAop {

    private static Logger logger = LoggerFactory.getLogger(ResponseResultAop.class);

    /**
     * 切点
     */
    private static final String POINTCUT = "execution(public * com.xjscrm.console.web..*.*(..))";

    @Around(POINTCUT)
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行目标方法,获得返回值
        Object result = joinPoint.proceed();

        //    @NoResponseResult注解的方法，直接返回
        if (joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName(), ((MethodSignature) joinPoint.getSignature()).getParameterTypes()).isAnnotationPresent(NoResponseResult.class)) {
            return result;
        }

        Object responseResult = null;
        try {
            String traceId = MDC.get("traceId");
            responseResult = new ResponseResult(ResponseCode.SUCCESS, null, result,traceId);
        } catch (Exception e) {
            logger.error("err:", e);
        }
        return responseResult;
    }

    /**
     * 打印入参以及方法名
     * @param joinPoint
     */
    @Before(POINTCUT)
    public void logInputParams(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        logger.info("MethodName: {},Input parameters: {}",methodName, Arrays.toString(args));
    }
}
